package com.pethospital.interceptor;

import cn.hutool.core.util.StrUtil;
import com.pethospital.exception.BusinessException;
import com.pethospital.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        log.info("拦截请求: {} {}", request.getMethod(), requestURI);
        
        // 获取token
        String token = request.getHeader("Authorization");
        log.info("获取到的Authorization头: {}", token);
        
        if (StrUtil.isBlank(token)) {
            log.warn("Token为空，拒绝访问: {}", requestURI);
            throw new BusinessException(401, "未登录");
        }

        // 规范化token格式，去掉Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
            log.info("去掉Bearer前缀，实际Token: {}", token);
        }

        // 解析token
        log.info("开始解析Token...");
        Claims claims = jwtUtil.getClaimsByToken(token);
        
        if (claims == null) {
            log.warn("Token解析失败，无法提取Claims: {}", token);
            throw new BusinessException(401, "登录已过期，请重新登录");
        }
        
        // 检查token是否过期
        boolean isExpired = jwtUtil.isTokenExpired(claims);
        log.info("Token是否过期: {}", isExpired);
        
        if (isExpired) {
            log.warn("Token已过期，拒绝访问: {}", requestURI);
            throw new BusinessException(401, "登录已过期，请重新登录");
        }

        // 将用户信息存入request
        Long userId = claims.get("userId", Long.class);
        Integer userType = claims.get("userType", Integer.class);
        
        log.info("从Token中提取用户ID: {}, 用户类型: {}", userId, userType);
        
        request.setAttribute("userId", userId);
        request.setAttribute("userType", userType);
        
        log.info("请求验证通过: {} => userId: {}, userType: {}", requestURI, userId, userType);
        return true;
    }
} 